package com.skin.onlineschool.springclond.gateway.Filter;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;

import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.util.StringUtils;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.netflix.zuul.http.HttpServletRequestWrapper;
import com.netflix.zuul.http.ServletInputStreamWrapper;

import lombok.extern.slf4j.Slf4j;

/**   
 * @ClassName:  RonterFilter   
 * @Description:tonken有效性检测  
 * @author: huoxicai
 * @date:   2020年4月27日 上午9:48:36      
 * @Copyright:  
 */
@Slf4j
public class RonterFilter extends ZuulFilter {

    /**
     * 获取 request 里传递的 token
     *
     * @param request
     * @return
     */
    public static String getTokenByRequest(HttpServletRequest request) {
        String token = request.getParameter("token");
        if (token == null) {
            token = request.getHeader("X-Access-Token");
        }
        return token;
    }

	@Override
	public boolean shouldFilter() {
		return false;
//		String uri = RequestContext.getCurrentContext().getRequest().getServletPath();
//		if (uri.contains("/usercenter")) {
//			String[] urlList=uri.split("/usercenter");
//			if(urlList.length>2)
//			{
////				if(FilterMapSingleton.getInstance().IsAuthUserCenterFilter(urlList[1]))
////				{
////					return false;
////				}
//			}
//		}
//		if (uri.contains("/api")) {
//			// 不鉴权
//			return false;
//		}
//		return true;
	}

	@Override
	public Object run() throws ZuulException {
		RequestContext ctx = RequestContext.getCurrentContext();
		String uri = RequestContext.getCurrentContext().getRequest().getServletPath();
		log.info("请求地址" + uri);
		HttpServletRequest request = ctx.getRequest();
		String userNo = null;
		try {
			userNo = JwtUtil.getUseridByToken(request);
		} catch (Exception e) {
			log.error("系统异常", e.getMessage());
			ctx.setSendZuulResponse(false);
			resp(ctx, e.getMessage(),500);
			return null;
		}
		// 参数封装
		try {
			ctx.setRequest(requestWrapper(request, userNo));
		} catch (IOException e) {
			log.error("封装参数异常", e.getMessage());
			ctx.setSendZuulResponse(false);
			resp(ctx, "系统异常，请重试");
		}
		return null;
	}
	
	private HttpServletRequestWrapper requestWrapper(HttpServletRequest request, String userNo) throws IOException {
		Map<String, Object> map = getParamMap(request);
		map.put("userId", userNo);
		String newBody = JSONUtil.toJSONString(map);
		log.info("转发参数={}", newBody);
		final byte[] reqBodyBytes = newBody.getBytes();
		return new HttpServletRequestWrapper(request) {
			@Override
			public BufferedReader getReader() throws IOException {
				return new BufferedReader(new InputStreamReader(getInputStream()));
			}

			@Override
			public ServletInputStream getInputStream() throws IOException {
				return new ServletInputStreamWrapper(reqBodyBytes);
			}

			@Override
			public int getContentLength() {
				return reqBodyBytes.length;
			}

			@Override
			public long getContentLengthLong() {
				return reqBodyBytes.length;
			}
		};
	}
	@SuppressWarnings("unchecked")
	private static TreeMap<String, Object> getParamMap(HttpServletRequest request) {
		TreeMap<String, Object> paramMap = new TreeMap<>();
		Map<String, String[]> map = request.getParameterMap();
		for (String key : map.keySet()) {
			paramMap.put(key, map.get(key)[0]);
		}
		if (paramMap.isEmpty()) {
			DataInputStream in = null;
			try {
				in = new DataInputStream(request.getInputStream());
				byte[] buf = new byte[request.getContentLength()];
				in.readFully(buf);
				String t = new String(buf, "UTF-8");
				if (StringUtils.hasText(t)) {
					return new TreeMap<String, Object>(JSONUtil.parseObject(t, TreeMap.class));
				}
			} catch (Exception e) {
				log.error("获取不到任何参数");
			} finally {
				if (null != in)
					try {
						in.close();// 关闭数据流
					} catch (IOException e) {
						log.error("关闭数据流异常");
					}
			}
		}
		return paramMap;
	}
	@Override
	public String filterType() {
		return FilterConstants.PRE_TYPE;
	}
	private void resp(RequestContext ctx, String msg) {
		ctx.getResponse().setCharacterEncoding("UTF-8");
		ctx.setResponseBody("{\"msg\":\""+msg+"\"}");
	}

	private void resp(RequestContext ctx, String msg, int code) {
		ctx.getResponse().setCharacterEncoding("UTF-8");
		ctx.setResponseBody("{\"code:\",\"500\",\"msg\":\""+msg+"\"}");
	}

	@Override
	public int filterOrder() {
		// TODO Auto-generated method stub
		return FilterConstants.PRE_DECORATION_FILTER_ORDER - 1;
	}

}
